<%@page import="itsm.isperp.framework.core.context.ContextHolder"%>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="isperp" uri="/WEB-INF/tlds/isperp.tld"%>


<link rel="stylesheet" type="text/css"
	href="js/libs/layer/skin/layim.css" rel="stylesheet" />

<script type="text/javascript" src="js/sockjs-0.3.4.js"></script>
<script type="text/javascript" src="js/stomp.js"></script>
<script type="text/javascript" src="js/jquery.json-2.2.min.js"></script>

<style>
<!--
.chat-name {
	font-weight: bold; color: #555
}

.user-chat {
	padding: 10px; background: #f2f9fe
}

.chat-send-btn,.chat-create-btn {
	padding: 8px; width: 80px;
}

.chat-send-btn {
	margin-right: 10px
}

.we-chat {
	padding: 10px;
}

.message-input {
	width: 580px; padding: 8px;
}

.message-content-box {
	height: 380px; overflow-y: scroll; border: 1px solid #eaeaea; margin-bottom: 15px
}

.layim_chatview {
	overflow: auto;
}

.layim_chatuser {
	padding: 3px
}

.layim_tool .layim_seechatlog {
	position: relative; float: right; line-height: 20px; margin-top: 5px
}
-->
</style>


<div id="tabbedBoxChat" class="box tabbedBox tabbedBoxFixed" style="max-width:100%">
	<div class="header">
		<ul id="tabbedBoxChatUl">
			<c:forEach items="${chattings }" var="entity">
				<li class="with-icon"><a
					onclick="showChats('${entity.openid}')" id="a_${entity.openid}"
					data-openid="${entity.openid}" data-loaded="0"
					href="#c_${entity.openid}">${entity.name}<span
						id="s_${entity.openid}"
						style="display:none; color:red;font-weight:700;font-size: 20px;line-height: 10px">·</span>
				</a></li>
			</c:forEach>
		</ul>
		<h2>&nbsp;</h2>
	</div>
	<div id="tabContent" style="padding:10px" class="content tabbed">

		<c:forEach items="${chattings }" var="entity">


			<div class="layim_chat" id="c_${entity.openid}">
				<div class="layim_chatarea">
					<ul class="layim_chatview layim_chatthis" id="v_${entity.openid}"></ul>
				</div>
				<div class="layim_tool">
					<a href="javascript:;" class="layim_seechatlog nui-txt-link"
						onclick="createIncident('${entity.openid}');"> 创建事件单</a> <a
						href="javascript:;" class="layim_seechatlog nui-txt-link hidden"
						onclick="applyToIncident('${entity.openid}');">附加到事件</a>
				</div>
				<textarea class="layim_write" id="i_${entity.openid}"
					placeholder="请输入回复内容..."></textarea>
				<div class="layim_send">
					<a class="layim_sendbtn" href="javascript:;"
						onclick="sendMessage('${entity.openid}');">&nbsp;&nbsp;发送</a>
				</div>
			</div>

		</c:forEach>
	</div>

</div>
<script type="text/javascript">
	function createIncident(openid) {
		var url = "incident/incident/newIncidentEdit?openid=" + openid + "&type=new";
		isperp.openDialog({
			contentUrl : url,
			width:1000,
			height:600,
		});
	}

	function applyToIncident(openid) {

		//将关联的openid的数据附加到事件单的详细信息中
		var url = "incident/incident/apply?openid=" + openid;
		isperp.openDialog({
			contentUrl : url
		});
	}
</script>

<script type="text/javascript">
var ws,wsforchars,wsurl="<%=ContextHolder.getWebServerName()%>";
	var litemplate = '<li class="with-icon">' + '<a onclick="showChats(\'{entity.openid}\')" id="a_{entity.openid}" data-openid="{entity.openid}" data-loaded="0" href="#c_{entity.openid}">{entity.name}<span id="s_{entity.openid}"'
    	 +' style="display:none; color:red;font-weight:700;font-size: 20px;line-height: 10px">·</span></a></li>';

	var contenttemplate =
			'<div class="layim_chat" id="c_{entity.openid}">'
		     +'<div class="layim_chatarea">'
			 +'<ul class="layim_chatview layim_chatthis" id="v_{entity.openid}"></ul>'
			 +'</div>'
			 +'<div class="layim_tool">'
			 +'	<a href="javascript:;" class="layim_seechatlog nui-txt-link"'
			 +'		onclick="createIncident(\'{entity.openid}\');"> 创建事件单</a> <a'
			 +'		href="javascript:;" class="layim_seechatlog nui-txt-link hidden"'
			 +'		onclick="applyToIncident(\'{entity.openid}\');">附加到事件</a>'
			 +'</div>'
			 +'<textarea class="layim_write" id="i_{entity.openid}"'
			 +'	placeholder="请输入回复内容..."></textarea>'
			 +'<div class="layim_send">'
			 +'	<a class="layim_sendbtn" href="javascript:;"'
			 +'		onclick="sendMessage(\'{entity.openid}\');">&nbsp;&nbsp;发送</a>'
			 +'</div>'
			 +'</div>';
			
	var imgTemplate = '<img src="{src}">';
	var audioTemplate = '<object type="application/x-shockwave-flash" data="js/libs/player/dewplayer-multi.swf?mp3={src}" width="240" height="20" id="dewplayer-multi"><param name="wmode" value="transparent" /><param name="movie" value="js/libs/player/dewplayer-multi.swf?mp3={src}" /></object>';

	//处理消息内容
	//
	function renderChat(frame) {
		var v = JSON.parse(frame.body);
		var $vpanel = $("#v_" + v.openid);

		if ($vpanel.length == 0) {
			var liHtml = litemplate.replaceAll("{entity.openid}", v.openid).replaceAll("{entity.name}", v.senderName);
			var contentHtml = contenttemplate.replaceAll("{entity.openid}", v.openid).replaceAll("{entity.name}", v.senderName);
			$("#tabbedBoxChatUl").append(liHtml);
			$("#tabContent").append(contentHtml);
			$vpanel = $("#v_" + v.openid);

			$("#tabbedBoxChat").tabs();
		}

		$vpanel.append(getChatHtml(v));

		//判断用户当前窗口
		$vpanel.scrollTop($vpanel[0].scrollHeight);

		var isCurrent = $("#a_" + v.openid).parent().hasClass("current");

		if (!isCurrent) {
			$("#s_" + v.openid).show();
		}
		//判断当前是否存在聊天tab，如果没有则添加

	};
	
	
	function getContentHtml(v,msgContent){
		var html='<li class="'+ (v.sendFrom === 'user' ? 'layim_chateme' : '') +'">'
          +'<div class="layim_chatuser">';
        if(v.sendFrom === 'user'){
            html+= '<span class="layim_chattime">'+ v.sendTime +'</span>'
                   +'<span class="layim_chatname">'+  v.senderName +'</span>';
        } else {
        	html+= '<span class="layim_chatname">'+ v.senderName +'</span>'
                   +'<span class="layim_chattime">'+ v.sendTime +'</span>';      
        }

        html  +='</div>'
        +'<div class="layim_chatsay">'+ msgContent +'<em class="layim_zero"></em></div>'
    	+'</li>';
    	
    	return html;
	};

	function getChatHtml(v) {
		var msgContent = v.data || v.sendContent;
		switch (v.msgType) {
		case "text":
			break;
		case "link":
			break;
		case "image":
			msgContent = imgTemplate.replaceAll("{src}", msgContent);
			break;
		case "voice":
		case "video":
			msgContent = audioTemplate.replaceAll("{src}", msgContent);
			break;
		default:
			break;
		}

	 
		
    
		return getContentHtml(v,msgContent);

	}

	function addChatTab() {
		var liHml, contentHtml;

	}

	var socket = new SockJS(wsurl + "websocket/");
	var stompClient = Stomp.over(socket);

	var connectCallback = function() {
		stompClient.subscribe('/chatMessage/result', renderChat);
	};

	var errorCallback = function(error) {
		isperp.alert(error);
	};

	stompClient.connect("<%=ContextHolder.getLoginUsername()%>", "123", connectCallback, errorCallback);
	var sendMessage = function(openid) {
		var inputBox = $("#i_" + openid);
		var iVal = inputBox.val();
		if (iVal) {
			var jsonstr = JSON.stringify({
				'data' : iVal,
				'sendFrom' : 'user',
				"senderName" : '${name}',
				'openid' : openid
			});

			stompClient.send("/socket/chat/send", {}, jsonstr);
			inputBox.val('');
		} else {
			isperp.alert('请输入回复内容！');
		}
	};

	function showChats(openid) {
		//判断是否第一次点开
		var loaded = $("#a_" + openid).data("loaded");
		if (loaded == '0') {
			$("#v_" + openid).html("载入聊天记录中，请稍候...");
			loadChats(openid);
		}
		$("#s_" + openid).hide();
	}

	function loadChats(openid) {
		$.get("wechat/chat/listChats", {
			"openid" : openid
		}, function(data) {
			var html = "";
			$(data).each(function(index, item) {
				html += getChatHtml(item);

			});
			var $vpanel = $("#v_" + openid);
			$vpanel.html(html);
			$("#a_" + openid).data("loaded", "1");

			$vpanel.scrollTop($vpanel[0].scrollHeight)
		});
	}

	$("#tabbedBoxChatUl a:first").click();

	function relpayAudio(obj) {
		var au = $(obj).prev()[0];
		if (au.currentTime) {
			au.currentTime = 0;
		}
		au.play();
		return false;

	}
</script>